<?php
include_once 'conn.php';
$page = $_POST['page'];
$perPage = $_POST['perPage'];
// 第1页：从0开始。第2页：从5开始，(页数-1)*每页的条数
$startIndex = ($page - 1) * $perPage;
$sql = "SELECT
	main.*,
CASE
	WHEN sub.replyNumbers IS NULL THEN
	'暂无回复' ELSE sub.replyNumbers 
	END replyNumbers,
	CASE WHEN sub.nickname is NULL then '暂无回复' else sub.nickname end replyNickName,
    case when sub.posttime is NULL then '' else sub.posttime end lastReplyTime,
     case when sub.posttime is NULL then main.posttime else sub.posttime end lastReplyTimeOrder  
FROM
	(
	SELECT
		m.id,
		m.title,
		m.posttime,
		m.hits,
		m.istop,
		u.nickname as postNickName
	FROM
		maintopic m,
		userinfo u 
	WHERE
		m.userid = u.id 
	) main
	LEFT JOIN (
	SELECT
		r.*,
		s.posttime,
		u.nickname 
	FROM
		( SELECT maintopicid, count( 1 ) AS replyNumbers, max( id ) AS lastReplyID FROM subtopic GROUP BY maintopicid ) r,
		userinfo u,
		subtopic s 
	WHERE
		r.lastReplyID = s.id 
	AND s.userid = u.id 
) sub ON main.id = sub.maintopicid
ORDER BY istop desc,lastReplyTimeOrder desc,posttime desc,id desc limit $startIndex,$perPage";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)){
    $a['error'] = 0;
    $a['info'] = mysqli_fetch_all($result,MYSQLI_ASSOC);
}
else{
    $a['error'] = 1;
    $a['errMsg'] = '没有更多内容了！';
}
echo json_encode($a);
